<template>
  <div style="width: 80%">
    <!-- 验证码登录弹窗 -->
    <van-popup v-model="show" style="width: 100%;height: 100%;padding: 1.6em;border-radius: 1em;">
      <div class="box">
        <div v-show="!showYzm" class="dhhm-box">
          <div class="header-box">
            绑定手机号
          </div>
          <div class="form-box">
            <input ref="_phone" class="field-ipt" v-model="phone" placeholder="请输入电话号码"
              :class="[isFocus ? 'isFocus' : '', isPhoneValid || isPhoneValid === '' ? '' : 'error']"
              @focus="handelfocus" @blur="onBlur">
            <div v-show="!isPhoneValid && isPhoneValid !== ''" style="font-size: 12px;color: red;padding: 0.7em 0 0 0">
              请输入正确的手机号
            </div>
            <div class="form-item">
              <div style="width: calc(100% - 120px)">
                <!--                <div style="margin-right: 10px;width: max-content">验证码</div>-->
                <input ref="_phone" class="field-ipt2" v-model="txCode" placeholder="请输入验证码"
                  :class="[isFocus2 ? 'isFocus' : '']" @focus="handelfocusTx" @blur="onBlurTx">
                <div v-show="yamtxpass !== '' && !yamtxpass" style="font-size: 12px;color: red;padding: 0.7em 0 0 0">
                  请输入正确验证码
                </div>
              </div>
              <Captcha ref="_Captcha" @update:code="updatecode" style="width: 120px" />
            </div>
          </div>
        </div>
        <div v-show="showYzm" class="yzm-box">
          <div style="text-align: center;padding: 2em 0 3.6em 0;position: relative">
            <div style="font-size: 1.5em;font-weight: bold;padding-bottom: 0.6em;color: #1fc170">
              顺汽巴士
            </div>
            <div style="font-size: 12px">
              欢迎注册顺汽巴士，提供商旅出行服务
            </div>
            <img src="@/assets/images/dotright.png" @click="onPreve" style="width: 43px; margin: 0 0 0 -16px;position: absolute;top: 1em;left: 0">
          </div>
          <div>
            <div class="yzm-header">
              <div>请输入验证码</div>
              <span class="xxs">验证码已发送159****9553，请在下方输入4位验证码</span>
            </div>
          </div>
          <div class="yam-input-box">
            <input v-for="(item, index) in 6" :key="index" type="number" v-model="code[index]"
              @input="handleInput(index)" @keydown="handleKeyDown(index, $event)" maxlength="1" ref="codeInput"
              class="code-input yam-field-ipt" />
          </div>
          <div v-if="smsCodeError" :class="{smsCodeError}" style="text-align: center;color: red;font-size: 12px;padding: 10px 0 0 0">验证码错误</div>
          <div key="chongfa" v-if="!shcf" class="chongfa">{{ countDown }}s后重发</div>
          <span key="onnext2" v-if="shcf" @click="onNext2" class="onnext2">重新发送</span>
        </div>
        <div style="display: flex;justify-content: center;margin: 2em 0 0 0">
          <button class="fdx" :class="{ isPhoneValid: isPhoneValid }" v-show="!showYzm"
            @click="onNext(isPhoneValid && yxCodePass)">发送短信验证码</button>
<!--          <button v-show="showYzm" @click="onPreve">上一步</button>-->
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { Popup } from 'vant';
import Captcha from "./Captcha.vue";
import axios from 'axios';
import { Toast } from 'vant';
import {SendVerificationCodeSMS, SubmitVerificationCode} from "@/request/api";
const request = axios.create({
  timeout: 60000,
  baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_URL : window.webConfig.webApiBaseUrl
});
const countDown2 = 60
export default {
  name: "TabChuang",
  props: ['userInfo', 'showHome', 'setyyy'],
  components: {
    [Popup.name]: Popup,
    Captcha
  },
  data() {
    return {
      txCode2: '',
      txCode: '',
      show: false,
      phone: '',
      isPhoneValid: '', // 标记手机号是否校验通过
      isFocus: false,
      code: ['', '', '', '', '', ''], // 存储4位验证码
      isFocus2: false,
      showYzm: false,
      countDown: countDown2,          // 倒计时（初始值根据需求调整）
      timer: null,             // 定时器引用
      yamtxpass: '',
      shcf: false,
      smsCodeError: false
    };
  },
  methods: {
    updatecode(e) {
      this.txCode2 = e
    },
    checkPhone() {
      // 简单的手机号正则校验，可根据实际需求调整正则规则
      const reg = /^1[3-9]\d{9}$/;
      this.isPhoneValid = reg.test(this.phone);
    },
    init() {
      this.show = true
      this.$nextTick(function () {
        this.$refs._phone.focus()
      })
    },
    handelfocus() {
      console.log('聚焦')
      this.isFocus = true
    },
    onBlur() {
      console.log('失焦')
      this.isFocus = false
      this.checkPhone()
    },
    handelfocusTx() {
      console.log('聚焦')
      this.yamtxpass = true
      this.isFocus2 = true
    },
    onBlurTx() {
      console.log('失焦')
      this.isFocus2 = false
    },
    // 启动倒计时
    startCountDown() {
      this.countDown = countDown2
      console.log('this.countDown',this.countDown)
      this.shcf = false
      if (this.timer) clearInterval(this.timer)
      this.timer = setInterval(() => {
        if (this.countDown > 1) {
          this.countDown--
          console.log('2',this.countDown)
        } else {
          console.log('1',this.countDown)
          clearInterval(this.timer)
          this.$refs._Captcha.refreshCode()
          this.txCode = ''
          this.shcf = true
        }
      }, 1000)
    },
    // 输入事件：自动聚焦到下一个输入框
    handleInput(index) {
      if (this.code[index].length === 1 && index < 5) {
        this.$refs.codeInput[index + 1].focus()
      }
    },

    // 按键事件：退格时聚焦到前一个输入框
    handleKeyDown(index, event) {
      if (event.key === 'Backspace' && this.code[index] === '' && index > 0) {
        event.preventDefault() // 阻止默认退格行为
        this.$refs.codeInput[index - 1].focus()
      }
    },
    // 发送验证码短信
    sendVerificationCodeSMSFn() {
      return new Promise((resolve) => {
        SendVerificationCodeSMS({
          "db_id": process.env.NODE_ENV === 'development' ? process.env.VUE_APP_DBID : window.webConfig.DB_ID,
          "system_id": process.env.NODE_ENV === 'development' ? process.env.VUE_APP_SYSTEMID * 1 : window.webConfig.SYSTEM_ID,
          phone: this.phone,
          reg_id: this.userInfo.userid,
          "customer_id_source": process.env.NODE_ENV === 'development' ? process.env.VUE_APP_CUSTOMERIDSOURCE : window.webConfig.customer_id_source
        }).then(res => {
          resolve(res)
        })
      })
    },
    // 提交验证码
    submitVerificationCodeFn(code) {
      return new Promise((resolve) => {
        SubmitVerificationCode({
          "code": code,
          phone: this.phone,
        }).then(res => {
          resolve(res)
        })
      })
    },
    async onNext(e) {
      if (e) {
        this.yamtxpass = true
        this.showYzm = true
        this.$nextTick(() => {
          this.$refs.codeInput[0].focus()
          if (this.countDown === countDown2 || this.countDown === 1) {
            this.sendVerificationCodeSMSFn().then(() => {
              this.startCountDown()
            })
          }
        })
      } else {
        this.yamtxpass = false
        this.txCode = ''
        this.$refs._Captcha.refreshCode()
      }
    },
    async onNext2() {
      this.showYzm = false
    },
    clearIntervalFn() {
      this.timer && clearInterval(this.timer)
      this.countDown = countDown2
    },
    onPreve() {
      if (this.countDown === 1) {
        console.log('this.countDown === 0')
        this.countDown = countDown2
        this.shcf = false
        this.$nextTick(() => {
          this.$refs._Captcha.refreshCode()
          this.txCode = ''
        })
      }
      this.showYzm = false
    },
    async checkCode(e) {
      const res = await this.submitVerificationCodeFn(e.toString())
      if (res.errcode === 0) {
        this.smsCodeError = false
        await this.handleNext()
      } else {
        // alert('请输入正确的验证码')
        this.smsCodeError = true
        this.code = ['', '', '', '', '', '']
        this.$refs.codeInput[0].focus()
      }
    },
    async handleNext() {
      this.showYzm = false
      Toast('绑定成功')
      this.setyyy()
      this.clearIntervalFn()
    }
  },
  computed: {
    yxCodePass() {
      return this.txCode2.toLowerCase() === this.txCode.toLowerCase()
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    code(newVal) {
      const codeStr = newVal.join('')
      if (codeStr.length === 6) {
        this.checkCode(codeStr)
      }
    }
  },
  beforeDestroy() {
    // 清除定时器，避免内存泄漏
    this.clearIntervalFn()
  }
};
</script>
<style scoped lang="less">
.box {
  font-size: 1.4em;

  .yzm-box {
    margin: 1em 0 0 0;
    padding: 0 1.4em;

    .yzm-header {
      margin-bottom: 1.4em;
    }

    .xxs {
      font-size: 0.8em;
      color: #999;
    }

    .chongfa {
      text-align: center;
      color: #999;
      font-size: 0.8em;
      margin: 1em 0 0 0;
    }
  }

  .yam-input-box {
    display: flex;
    align-items: center;
    width: 100%;
    gap: 1em;
    justify-content: center;

    .yam-field-ipt {
      border: 1px solid #eee;
      height: 2em;
      width: 2em;
      text-align: center;
    }
  }

  .header-box {
    background: #1fc170;
    color: #fff;
    line-height: 40px;
    padding: 0.2em 1em;
  }

  button {
    background: #1fc170;
    color: #fff;
    border: none;
    width: 80%;
    padding: 0.8em 0;
    border-radius: 100px;
    margin: 2em 0 0 0;
    //position: absolute;
    //bottom: 40px;
    //left: 50%;
    //transform: translateX(-50%);
  }

  .form-box {
    padding: 0 1em;
    margin: 1.4em 0 0 0;

    .field-ipt {
      border-bottom: 1px solid #eee;
      width: 100%;
      padding: 0 0 0.8em 0;

      &.isFocus {
        border-color: #1fc170;
      }

      &.error {
        border-color: red;
      }
    }

    .form-item {
      display: flex;
      align-items: center;
      padding: 1.2em 0;
      justify-content: space-between;
    }
  }
}

.box .fdx {
  background: hsl(150deg 72% 44% / 40%);
}

.box .isPhoneValid {
  background: #1fc170;
}

.onnext2 {
  text-align: center;
  padding: 10px 0;
  font-size: 12px;
  color: blue;
  display: inline-block;
  width: 100%;
}
</style>
